/*
 * @lc app=leetcode.cn id=142 lang=java
 *
 * [142] 环形链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(null == head || null == head.next){
            return null;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;
        boolean hasCycle = false;

        while(null!=fast && null!=fast.next){
            if(slow == fast){
                hasCycle = true;
                break;
            }
            slow = slow.next;
            fast = fast.next.next;
        }

        if(!hasCycle){
            return null;
        }
        //一个从头开始走，一个从相遇点开始走，两者相遇的地方即环的起点
        ListNode slow2 = head;
        while(slow2 != slow){
            slow = slow.next;
            slow2 = slow2.next;
        }
        return slow2;
    }
}
// @lc code=end

